<template>
  <div class="actions-container">
    <el-card class="approval-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon><EditPen /></el-icon>
          <span>审批操作</span>
        </div>
      </template>

      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <!-- 审批意见 -->
        <el-form-item label="审批意见" prop="comment">
          <el-input
            v-model="formData.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见..."
            maxlength="300"
            show-word-limit
            :disabled="loading"
          />
        </el-form-item>

        <!-- 审批提示 -->
        <el-form-item>
          <el-alert
            :title="approvalTips.title"
            :description="approvalTips.description"
            type="info"
            :closable="false"
            show-icon
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button
            type="success"
            :loading="loading && actionType === 'approve'"
            @click="handleApprove"
            :disabled="loading || !formData.comment.trim()"
            :icon="Check"
          >
            {{ loading && actionType === 'approve' ? '审批中...' : '批准申请' }}
          </el-button>
          <el-button
            type="danger"
            :loading="loading && actionType === 'reject'"
            @click="handleReject"
            :disabled="loading || !formData.comment.trim()"
            :icon="Close"
          >
            {{ loading && actionType === 'reject' ? '驳回中...' : '驳回申请' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' // 引入Element Plus消息组件
import { EditPen, Check, Close } from '@element-plus/icons-vue' // 引入图标
import { useApplicationStore } from '@/store/application'
import type { ReimbursementApplication } from '@/services/models'

const props = defineProps<{ application: ReimbursementApplication }>()
const store = useApplicationStore()

// 表单数据
const formData = reactive({
  comment: '',
})

// 表单验证规则
const formRules = {
  comment: [
    { required: true, message: '请填写审批意见', trigger: 'blur' },
    { min: 5, max: 300, message: '意见长度在 5 到 300 个字符', trigger: 'blur' },
  ],
}

const actionType = ref<'approve' | 'reject' | null>(null)
const formRef = ref() // 表单引用

// 当前用户角色
const currentRole = computed(() => store.currentUser.role)

// 加载状态
const loading = computed(() => store.loading)

// 审批提示信息
const approvalTips = computed(() => {
  const tips = {
    head: {
      title: '部门主管审批提示',
      description:
        '请审核费用项目是否在部门预算内，报销金额是否在规定额度内。重点关注费用合理性和必要性。',
    },
    finance: {
      title: '财务审核提示',
      description:
        '请审核发票真实性和合规性，核对报销金额计算是否正确。确保所有费用都有相应的发票支持。',
    },
    gm: {
      title: '总经理终审提示',
      description:
        '请从公司整体费用把控角度进行最终审批。综合考虑申请的必要性、合理性和公司财务状况。',
    },
  }
  return tips[currentRole.value] || { title: '审批提示', description: '请认真审核申请内容' }
})

// 获取下一级审批流程消息
const getNextStepMessage = () => {
  const { status } = props.application
  const { role } = store.currentUser

  if (status === 'PENDING_HEAD_REVIEW' && role === 'head') {
    return '审批通过！申请已进入财务审核阶段。'
  }
  if (status === 'PENDING_FINANCE_REVIEW' && role === 'finance') {
    return '审批通过！申请已进入总经理终审阶段。'
  }
  if (status === 'PENDING_GM_REVIEW' && role === 'gm') {
    return '审批通过！申请已完成，将自动完成打款流程。'
  }

  return '审批通过！申请已进入下一级审批流程。'
}

// 批准申请
const handleApprove = async () => {
  if (!formRef.value) return
  // 表单验证
  const valid = await formRef.value.validate()

  // 如果验证失败，直接返回，不执行后续逻辑
  if (!valid) {
    return
  }
  try {
    // 确认审批操作
    await ElMessageBox.confirm('确定要批准这个申请吗？批准后将进入下一级审批流程。', '确认批准', {
      confirmButtonText: '确定批准',
      cancelButtonText: '取消',
      type: 'success',
    })

    actionType.value = 'approve'
    await store.approve(props.application.id, formData.comment)

    // 清空表单
    formData.comment = ''
    if (formRef.value && formRef.value.clearValidate) {
      formRef.value.clearValidate()
    }

    ElMessage({
      type: 'success',
      message: getNextStepMessage(),
      duration: 3000,
    })
  } catch (error: unknown) {
    if (error !== 'cancel') {
      ElMessage({
        type: 'error',
        message: `审批失败：${error instanceof Error ? error.message : '未知错误'}`,
        duration: 5000,
      })
    }
  } finally {
    actionType.value = null
  }
}

// 驳回申请
const handleReject = async () => {
  if (!formRef.value) return

  try {
    // 表单验证
    await formRef.value.validate()

    // 确认驳回操作
    await ElMessageBox.confirm('确定要驳回这个申请吗？驳回后申请人可以重新提交。', '确认驳回', {
      confirmButtonText: '确定驳回',
      cancelButtonText: '取消',
      type: 'warning',
    })

    actionType.value = 'reject'
    await store.reject(props.application.id, formData.comment)

    // 清空表单
    formData.comment = ''
    if (formRef.value && formRef.value.clearValidate) {
      formRef.value.clearValidate()
    }

    ElMessage({
      type: 'warning',
      message: '申请已驳回！申请人可以根据驳回理由重新提交。',
      duration: 3000,
    })
  } catch (error: unknown) {
    if (error !== 'cancel') {
      ElMessage({
        type: 'error',
        message: `驳回失败：${error instanceof Error ? error.message : '未知错误'}`,
        duration: 5000,
      })
    }
  } finally {
    actionType.value = null
  }
}
</script>

<style scoped>
.actions-container {
  max-width: 600px;
  margin: 0 auto;
}

.approval-card {
  border-radius: 12px;
  border: 2px solid #409eff;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-header .el-icon {
  font-size: 18px;
  color: #409eff;
}

/* 自定义表单样式 */
:deep(.el-form-item__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  padding: 12px 24px;
  margin-right: 12px;
}

:deep(.el-button--success) {
  background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
  border: none;
}

:deep(.el-button--success:hover) {
  background: linear-gradient(135deg, #5daf34 0%, #529b2e 100%);
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #f56c6c 0%, #e74c3c 100%);
  border: none;
}

:deep(.el-button--danger:hover) {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
}

/* 提示框样式 */
:deep(.el-alert) {
  border-radius: 8px;
  border: 1px solid #e1f3d8;
}

:deep(.el-alert--info) {
  background-color: #f0f9ff;
  border-color: #b3d8ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .actions-container {
    margin: 10px;
  }

  :deep(.el-form-item__label) {
    width: 80px !important;
  }

  :deep(.el-button) {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }
}

@media (max-width: 480px) {
  .card-header {
    font-size: 14px;
  }

  :deep(.el-form-item__label) {
    width: 70px !important;
    font-size: 14px;
  }
}
</style>
